<?php
$this->headLink(array('href' => '/cms/styles/style.css', 'rel' => "stylesheet", 'type' => "text/css"));
$this->headLink(array('href' => '/cms/styles/data-table.css', 'rel' => "stylesheet", 'type' => "text/css"));

$this->headScript()
	->appendFile('/cms/scripts/dojo/dojo.js','',array('djConfig'=> 'parseOnLoad:true, isDebug:false'))
	->setAllowArbitraryAttributes(true);

$this->headLink(array('href' => '/cms/scripts/shadowbox-3.0rc1/shadowbox.css', 'rel' => "stylesheet", 'type' => "text/css"));
$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/shadowbox-3.0rc1/shadowbox.js');

$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/content.js');
//$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/Popup.js');
$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/TableData.js');
$this->headScript(Zend_View_Helper_HeadScript::SCRIPT,"
	//var newsId = {$this->news_id};
	//filter_setup = ['from_date','".date('Y-m-d',mktime(0,0,0,date('m'),date('d')-10,date('Y')))."','to_date','".date('Y-m-d')."'];");
$this->headScript(Zend_View_Helper_HeadScript::SCRIPT,<<<EOD

dojo.require("dijit.InlineEditBox");
dojo.require("dojo.parser");
  
var shadowbox_callback = function () {};

reset_shadowbox_callback = function () {
	shadowbox_callback = function () {};
} 

Shadowbox.init({
    players:    ['html', 'iframe', 'img', 'swf'],
    onClose: function() { shadowbox_callback() }
});	

window.onload = function () {
	
	
	usersTable = new tableData('mainUsersTable');
	
    //столбик с логином пользователя
	usersTable.registerWidget('users_login',
		function (params) {
			var divEl = document.createElement('DIV');
			divEl.innerHTML = params['value'];
			divEl.setAttribute('dojoType','dijit.form.DateTextBox(');
			
/*			new dijit.InlineEditBox({
									autoSave:true,
									renderAsHtml:true,
									onChange: function (value) {
											dojo.xhrGet({
											    url: "/cms/news/change/id/"+params['id']+"/add_date/"+value,
											    load: function(response, ioArgs){
											      return response;
											    },
											    error: function(response, ioArgs){
											      alert(response);
											      return response;
											    },
											    handleAs: "text"
											  });
									
										}
								}, divEl);*/
			
			return divEl;
		});	
	
	//столбик с редактирование
	usersTable.registerWidget('users_edit',
		function (params) {
  		    var divEl = document.createElement('DIV');
			divEl.className = 'icon';
			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/document_pencil.png';
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
                Shadowbox.open({
			      player:     'iframe',
			      title:      'Редактирование пользователя',
			      content:    '/cms/users/edit/user_id/'+params['id'],
			      height:     450,
			      width:      750
			  });
			}
			divEl.appendChild(aEl);
			aEl.appendChild(imgEl);
			
			return divEl;
		});	
		
		
    //столбик со сменой пароля
	usersTable.registerWidget('users_pass',
		function (params) {
  		    var divEl = document.createElement('DIV');
			divEl.className = 'icon';
			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/key.png';
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
                Shadowbox.open({
			      player:     'iframe',
			      title:      'Смена пароля',
			      content:    '/cms/users/pass/user_id/'+params['id'],
			      height:     150,
			      width:      450
			  });
			}
			divEl.appendChild(aEl);
			aEl.appendChild(imgEl);
			
			return divEl;
		});	

	usersTable.registerWidget('users_email',
		function (params) {
			var divEl = document.createElement('div');
			divEl.setAttribute('dojoType','dijit.InlineEditBox');
			divEl.innerHTML = params['value']=='' ? 'Нет емайла' : params['value'];
			
			new dijit.InlineEditBox({
									autoSave:true,
									renderAsHtml:true,
									onChange: function (value) {
											dojo.xhrGet({
											    url: "/cms/users/change/id/"+params['id']+"/email/"+value,
											    load: function(response, ioArgs){
											      return response;
											    },
											    error: function(response, ioArgs){
											      alert(response);
											      return response;
											    },
											    handleAs: "text"
											  });
									
										}
								}, divEl);
			return divEl;
		});

    //флажок статуса пользователя
	usersTable.registerWidget('users_flags',
		function (params) {
			var divEl = document.createElement('DIV');
			divEl.className = 'icon';

			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/' + (params['value']=='0' ? params['img_off'] : params['img_on']);
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
					dojo.xhrGet({
						url: "/cms/users/flag/id/"+params['id']+"/flag/" + params['bit'],
						load: function(response, ioArgs) {
						  imgEl.src = '/cms/images/' + response; 
						  return response;
						},
						error: function(response, ioArgs){
						  alert("An error occurred, with response: " + response);
						  return response;
						},
						handleAs: "text",
						sync: true
					  });
				}
			
			divEl.appendChild(aEl);
			aEl.appendChild(imgEl);
			
			return divEl;
		});
		
	dojo.query('#newUserBtn').connect('onclick',
		function () {
			shadowbox_callback = function () {
		   		gotoPage(1);
		   		reset_shadowbox_callback();
		   	}
		   	
			Shadowbox.open({
			      player:     'iframe',
			      title:      'Добавление пользователя',
			      content:    '/cms/users/add',
			      height:     450,
			      width:      750
			  });
			  
			callData([]);
		});
		
		
    callData([]); //загружаем данные
}//onload
			
//загрузка пользователей
var callData = function (params) {
	dojo.xhrGet({
	    url: "/cms/users/widget/limit_from/"+limit_setup[0]+"/limit_amount/"+limit_setup[1]+'/'+params.join('/'),
	    load: function(responseObject, ioArgs){
	      var pagesPlace = document.getElementById('pagesPlace');
	      pagesPlace.innerHTML = '';
	      
	      //разбираемся со страницами
	      var total_pages = Math.ceil(responseObject['total_length']/rows_per_page);
	      
	      var appendPageAction = function (page) {
	        var aEl = document.createElement('A');
	      	aEl.innerHTML = i;
	      	aEl.href = 'javascript:;';
	      	aEl.onclick = function () { gotoPage(page) }
	      	return aEl;
	      }
	      
	      var appendDelimetr = function () {
	        var delimetr = document.createElement('SPAN');
	      	delimetr.innerHTML = '&nbsp;';
	      	return delimetr;
	      }
	      
	      
	      if (current_page>1) {
	      	var aEl = document.createElement('A');
	      	aEl.innerHTML = '&lt; Предыдущая';
	      	aEl.href = 'javascript:;';
	      	aEl.onclick = function () { gotoPage(current_page-1) }
	      	pagesPlace.appendChild(aEl);
	      	pagesPlace.appendChild(appendDelimetr());
	      }
	      
	      var start_from = current_page-3;
	      if (start_from>1) {
	      	var dots = document.createElement('SPAN');
	      	dots.innerHTML = '...&nbsp;';
	      	pagesPlace.appendChild(dots);
	      } else {
	      	start_from = 1;
	      }
	      for (var i=start_from;i<current_page;i++) {
	      	pagesPlace.appendChild(appendPageAction(i));
	      	
	      	pagesPlace.appendChild(appendDelimetr());
	      }
	      
	      var cur_pg = document.createElement('SPAN');
	      cur_pg.innerHTML = current_page;
	      pagesPlace.appendChild(cur_pg)
	      
	      pagesPlace.appendChild(appendDelimetr());
	      	
	      	
	      var end_to = current_page+3;
	      if (end_to>total_pages) end_to = total_pages;
	      
	      for (var i=current_page+1;i<=end_to;i++) {
	      	pagesPlace.appendChild(appendPageAction(i));
	      	
	      	pagesPlace.appendChild(appendDelimetr());
	      }
	      
	      if (end_to<total_pages) {
	        var dots = document.createElement('SPAN');
	      	dots.innerHTML = '...&nbsp;';
	      	pagesPlace.appendChild(dots);
	      }
	      
	      if (current_page<total_pages) {
	      	var aEl = document.createElement('A');
	      	aEl.innerHTML = 'Следующая &gt;';
	      	aEl.href = 'javascript:;';
	      	aEl.onclick = function () { gotoPage(current_page+1) }
	      	pagesPlace.appendChild(aEl);
	      	pagesPlace.appendChild(appendDelimetr());
	      }
	      
          usersTable.draw(responseObject['data']);		  
		  
		  //dojo.parser.parse(document.getElementById('mainNewsTable'));
		  
	      return responseObject;
	    },
	    error: function(response, ioArgs){
	      alert("An error occurred, with response: " + response);
	      return response;
	    },
	    handleAs: "json",
	    sync: true
	  });

}

var current_page = 1;
var rows_per_page = 10;
var limit_setup = [0,rows_per_page];

var filter_setup = new Array();
var MakeFilter = function () {
    filter_setup = [];
    if( document.getElementById('f_login').value )
        filter_setup = ['f_login', document.getElementById('f_login').value];
    if( document.getElementById('f_email').value )
	   filter_setup.push('f_email', document.getElementById('f_email').value);
    if( document.getElementById('f_status').value )
	   filter_setup.push('f_status', document.getElementById('f_status').value);
//	if (document.getElementById('publish_f').checked) {
//		filter_setup.push('publish_f','1');
//	}
	
	gotoPage(1);
}

var clearFilterFields = function(){
    document.getElementById('f_login').value = "";
    document.getElementById('f_email').value = "";
}


var gotoPage = function (page) {
	current_page = page;
	limit_setup = [(page-1)*rows_per_page,rows_per_page];
	callData(filter_setup);
}
EOD
);


$this->layout()->body_attr = 'class="modal"';
?>	


<form method="POST" action="" id="filterform">
<p class="stnd_font">
Логин:<input type="text" id="f_login" value="<?=$this->f_login?>" class="modalInput">
&nbsp;&nbsp;&nbsp;&nbsp;
E-Mail:</td><td><input type="text" id="f_email" value="<?=$this->f_email?>" class="modalInput">
<input type="button" style="width:130px" value="Фильтровать" class="okButton" onclick="MakeFilter()" />
</p>
<br />
<p class="stnd_font">Показать: 
    <a href="#" onclick="clearFilterFields();document.getElementById('f_status').value = '1is_vip'; MakeFilter();">VIP</a> 
    <a href="#" onclick="clearFilterFields();document.getElementById('f_status').value = '1blocked'; MakeFilter();">Блокированных</a> 
    <a href="#" onclick="clearFilterFields();document.getElementById('f_status').value = '0checked'; MakeFilter();">Непроверенных</a>
    <a href="#" onclick="clearFilterFields();document.getElementById('f_status').value = ''; MakeFilter();">Всех</a></p>
<input type="hidden" id="f_status" name="f_status" value = "">
</form>

<div style="float:right; margin-top: -8px; margin-bottom: 4px;"><button type="button" class="okButton" id="newUserBtn"><img src="/cms/images/plus.png" /> Добавить пользователя</button></div>
<p class="stnd_font">Страницы: <span id="pagesPlace">&nbsp;</span></p>
<table width="100%" cellspacing="0" class="table-data">
<thead>
  <tr>
    <th width="160" nowrap="nowrap" scope="col">Логин</th>
    <th nowrap="nowrap" scope="col">Е-майл</th>
  <?php //столбцы со статусом
    foreach ($this->flagNames as $index => $f) {
        if( $index != 'system' ){ 
    ?>
    <th><?=$f?></th>
  <?php }} ?>
    <th>Сменить пароль</th>
    <th width="34" nowrap="nowrap" scope="col">
    Профайл
    </th> <!-- столбик для редактирования-->
  </tr>
  <tr>
  </tr>
<?php //} ?>
  </tr>
</thead>
<tbody id="mainUsersTable"></tbody>
</table>
